package com.cr.crandroid.ui.home.rent;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import com.cr.crandroid.R;
import com.cr.crandroid.adapter.ImageAdapter;
import com.cr.crandroid.adapter.ImageAdapter2;
import com.cr.crandroid.adapter.ImageTitleNumAdapter;
import com.cr.crandroid.ui.person.user.LoginViewModel;
import com.cr.crandroid.utils.CommonConstant;
import com.cr.crandroid.utils.OConvertUtils;
import com.cr.crandroid.utils.OkHttpManager;
import com.cr.crandroid.vo.CarVo;
import com.cr.crandroid.vo.RentVo;
import com.google.android.material.snackbar.Snackbar;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HomeItemDetailFragment extends Fragment {

    private CarVo car;
    private Banner<?, BannerAdapter<?, ?>> banner;
    private AlertDialog alertDialog;
    private AlertDialog.Builder builder;
    private AddRentFragment addRentFragment;
    private LayoutInflater inflater;
    private ViewGroup container;
    private RentVo rent;
    private Button button;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.inflater = inflater;
        this.container = container;
        View root = inflater.inflate(R.layout.fragment_home_item_detail, container, false);
        TextView textView = root.findViewById(R.id.textView);
        TextView textView2 = root.findViewById(R.id.textView2);
        TextView textView3 = root.findViewById(R.id.textView3);
        TextView textView4 = root.findViewById(R.id.textView4);
        TextView textView5 = root.findViewById(R.id.textView5);
        TextView textView6 = root.findViewById(R.id.textView6);
        TextView textView7 = root.findViewById(R.id.textView7);
        TextView textView8 = root.findViewById(R.id.textView8);
        TextView textView9 = root.findViewById(R.id.textView9);
        TextView textView10 = root.findViewById(R.id.textView10);
        CircleImageView circleImageView = root.findViewById(R.id.circleImageView);
        button = root.findViewById(R.id.button);
        button.setOnClickListener(this::showMaterialAlertDialog);
        banner = root.findViewById(R.id.banner);
        banner.addBannerLifecycleObserver(this)
                .setPageTransformer(new ZoomOutPageTransformer())
                .start();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            list.add(R.drawable.pic_item_list_default);
        }
        banner.setAdapter(new ImageAdapter(list));
        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey("carVo")) {
            String carJson = arguments.getString("carVo");
            car = new Gson().fromJson(carJson, new TypeToken<CarVo>() {
            }.getType());
            if (car.getImage() != null)
                banner.setAdapter(new ImageAdapter2(Arrays.asList(car.getImage().split(",")), getContext()));
            textView.setText(car.getBrand());
            textView2.setText(car.getColor());
            textView3.setText(car.getSeatingCapacity());
            textView4.setText(car.getYear());
            textView5.setText("价值：  "+car.getPrice());
            textView6.setText("详情：  "+car.getDetail());
            textView7.setText(car.getRentalStart() + "至" + car.getRentalEnd());
            textView8.setText(car.getRealName());

            textView9.setText(Integer.parseInt(car.getSex()) == 1 ? "男" : "女");
            if (Integer.parseInt(car.getSex()) == 0)
                textView9.setText("未知");
            if (car.getSex().equals(CommonConstant.FEMALE))
                circleImageView.setImageResource(R.drawable.head_female);
            textView10.setText(car.getPhone());

            // 判断预约按钮是否显示
            switch (car.getIsRent()) {
                case CommonConstant.NOT_REND:
                    button.setVisibility(View.VISIBLE);
                    break;
                case CommonConstant.REND:
                    button.setVisibility(View.GONE);
                    break;

            }
            try {
                Date startDate;
                Date endDate;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date nowDate = new Date();
                startDate = sdf.parse(car.getRentalStart());
                endDate = sdf.parse(car.getRentalEnd());
                if (startDate.getTime() > nowDate.getTime()) {
                    button.setVisibility(View.GONE);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        builder = new AlertDialog.Builder(getContext())
                .setTitle("预约");
        addRentFragment = new AddRentFragment();
        builder.setInverseBackgroundForced(true);
        builder.setNegativeButton("确定", null);
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        return root;

    }

    // 显示预约对话框
    private void showMaterialAlertDialog(View view) {
        if (!LoginViewModel.user.has("id")) {
            Navigation.findNavController(view).navigate(R.id.action_homeItemDetailFragment_to_loginFragment);
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("carVo", new Gson().toJson(car, CarVo.class));
            builder.setView(addRentFragment.onCreateView(inflater, container, bundle, getActivity()));
            alertDialog = builder.create();
            alertDialog.show();
            alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (addRentFragment.judge()) {
                        rent = addRentFragment.getRent();
                        rent.setCarId(car.getId());
                        rent.setUserId(OConvertUtils.getString(LoginViewModel.user.get("id").toString()));
                        addRent(view);
                    }
                }
            });

        }

    }

    // 预约操作
    private void addRent(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpManager.postJ(CommonConstant.URL + "/rent/add", new Gson().toJson(rent), new Callback() {
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String res = response.body().string();
                        JsonObject result = JsonParser.parseString(res).getAsJsonObject();
                        if (Integer.parseInt(String.valueOf(result.get("code"))) != CommonConstant.ERROR) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    alertDialog.dismiss();
                                    button.setVisibility(View.GONE);
                                    Navigation.findNavController(getView()).navigate(R.id.action_homeItemDetailFragment_to_navigation_appointment);
                                    Snackbar.make(view, "预约成功!",
                                            Snackbar.LENGTH_LONG).show();
                                }
                            });
                        }else{
                            Snackbar.make(view, String.valueOf(result.get("message")), Snackbar.LENGTH_LONG).show();
                        }
                    }
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    }
                });
            }
        }).start();
    }

}